package com.eipc.util;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.androidpn.sdk.Constants;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.eipc.info.R;
import com.eipc.model.Response;
import com.eipc.model.SerInfoResponse;

public class HttpManager {
	private static final String DEFAULT_CHARSET = "utf8";
	private static final int timeoutConnection = 20000;
	private static final int timeoutSocket = 30000;

	public static String push(String url, boolean isGet,
			Map<String, Object> params) throws Exception {
		HttpClient client = new DefaultHttpClient();
		HttpParams hp = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(hp, timeoutConnection);
		HttpConnectionParams.setSoTimeout(hp, timeoutSocket);
		HttpResponse response;
		Log.i("-------start push----------", "start");
		if (isGet) {
			if (params != null) {
				Set<String> keys = params.keySet();
				StringBuffer parStr = new StringBuffer();
				String b = "?";
				for (String key : keys) {
					parStr.append(b
							+ URLEncoder.encode(key, DEFAULT_CHARSET)
							+ "="
							+ URLEncoder.encode(
									String.valueOf(params.get(key)),
									DEFAULT_CHARSET));
					b = "&";
				}
				url += parStr.toString();
				Log.i("-------start push----------", url);
			}
			HttpGet get = new HttpGet(url);
			get.setParams(hp);
			response = client.execute(get);
		} else {
			Log.i("-------start push url----------", url);
			HttpPost post = new HttpPost(url);
			post.setParams(hp);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			// 需要通过POST提交的参数
			if (params != null) {
				Set<String> keys = params.keySet();
				for (String key : keys) {
					nvps.add(new BasicNameValuePair(key, String.valueOf(params
							.get(key))));
				}
			}
			post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			Log.i("-------start push execute----------", "execute");
			response = client.execute(post);
			Log.i("-------start push execute----------", "execute fine");
			Log.i("-------start push execute----------", String
					.valueOf(response.getStatusLine().getStatusCode()));
		}

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			Log.i("-------start push execute----------", "fine if");
			HttpEntity entity = response.getEntity();
			Log.i("-------start push execute----------", "fine if 2");
			String s = EntityUtils.toString(entity, DEFAULT_CHARSET);
			Log.i("-------start push execute----------", "fine if 3");
			Log.i("-------response----------", s);
			return s;
		}
		return null;
	}

	public static String uploadFile(String url, Map<String, Object> params)
			throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		HttpParams hp = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(hp, 4 * 60 * 1000);
		HttpConnectionParams.setSoTimeout(hp, 5 * 60 * 1000);
		// 请求处理页面
		HttpPost httppost = new HttpPost(url);
		httppost.setParams(hp);
		MultipartEntity reqEntity = new MultipartEntity();
		if (params != null) {
			Set<String> keys = params.keySet();
			for (String key : keys) {
				Object param = params.get(key);
				if (param instanceof String) {
					reqEntity.addPart(key, new StringBody((String) param));
				} else if (param instanceof File) {
					reqEntity.addPart(key, new FileBody((File) param));
				} else if (param instanceof InputStream) {
					reqEntity.addPart(key, new InputStreamBody(
							(InputStream) param, "report.jpg"));
				}
			}
		}
		// 设置请求
		httppost.setEntity(reqEntity);
		// 执行
		HttpResponse response = httpclient.execute(httppost);
		if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			HttpEntity entity = response.getEntity();
			// 显示内容

			if (entity != null) {
				String res = EntityUtils.toString(entity);
				if (entity != null) {
					entity.consumeContent();
				}
				return res;
			}
		}
		return null;
	}

	public static Bitmap getURLBitmap(String url) {
		Log.e("------------getURLBitmap", "-----begin-----");
		Bitmap bitmap = null;
		URL imageUrl = null;
		try {
			imageUrl = new URL(url);
		} catch (MalformedURLException e) {
			Log.e("------------getURLBitmap", "error : ", e);
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(40000);
			conn.setReadTimeout(30000);
			Log.e("------------getURLBitmap", "-----begin connect-----");
			conn.connect();
			InputStream is = conn.getInputStream();
			int length = (int) conn.getContentLength();
			Log.e("------------getURLBitmap ContentLength :", "" + length);
			if (length != -1) {
				byte[] imgData = new byte[length];
				byte[] temp = new byte[512];
				int readLen = 0;
				int destPos = 0;
				while ((readLen = is.read(temp)) > 0) {
					System.arraycopy(temp, 0, imgData, destPos, readLen);
					destPos += readLen;
					// Log.e("------------getURLBitmap status
					// :",destPos+"/"+length);
				}
				bitmap = BitmapFactory.decodeByteArray(imgData, 0,
						imgData.length);
			}
			is.close();
			conn.disconnect();
		} catch (Exception e) {
			Log.e("------------getURLBitmap", "error : ", e);
		}
		return bitmap;
	}

	public static String insertImportNotice(Context context, int type,
			String[] personIds, String content, String sendType,
			String imageLocalUrl, InputStream in) throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("commType", String.valueOf(type));
		if (personIds != null) {
			String staIds = "";
			String prex = "";
			for (int i = 0; i < personIds.length; i++) {
				staIds += prex + personIds[i];
				prex = ",";
			}
			Log.i("-------staIds----------", staIds);
			parms.put("staIds", staIds);
		}
		parms.put("command.content", content);
		if (sendType != null || !"".equals(sendType)) {
			parms.put("command.sendType", sendType);
		} else {
			switch (type) {
			case 2:
				parms.put("command.sendType", "我要找茬");
				break;
			case 3:
				parms.put("command.sendType", "其他");
				break;
			}
		}
		parms.put("command.top", "true");
		SharedPreferences sdkPreferences = context.getSharedPreferences(
				Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
		String mobilID = sdkPreferences.getString(Constants.XMPP_USERNAME, "");
		parms.put("staff.mobileID", mobilID);

		Log.i("-------url----------", context
				.getString(R.string.url_control_center_send));
		Log.i("-------commType----------", "" + type);
		Log.i("-------command.content----------", content);
		Log.i("-------command.sendType----------", sendType);
		Log.i("-------command.top----------", "true");
		Log.i("-------staff.mobileID----------", mobilID);
		if (imageLocalUrl != null && !"".equals(imageLocalUrl)) {
			Log.i("-------imgFile----------", imageLocalUrl);
			File file = new File(imageLocalUrl);
			if (file.exists()) {
				Log.i("-------imgFile can Read : ----------", String
						.valueOf(file.canRead()));
				Log.i("-------imgFile can Write : ----------", String
						.valueOf(file.canWrite()));
				Log.i("-------imgFile is  Directory : ----------", String
						.valueOf(file.isDirectory()));
				Log.i("-------imgFile is  File : ----------", String
						.valueOf(file.isFile()));
			} else {
				Log.e("-------imgFile not exists----------", imageLocalUrl);
			}
			parms.put("imgFile", file);
			return uploadFile(context
					.getString(R.string.url_control_center_send), parms);
		} else if (in != null) {
			parms.put("imgFile", in);
			return uploadFile(context
					.getString(R.string.url_control_center_send), parms);
		} else {
			Log.i("-------InputStream in ----------", "in is null");
			return push(context.getString(R.string.url_control_center_send),
					false, parms);
		}
	}

	public static String replyCommand(String url, String commandId,
			String content, String mobilID, String time) throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("command.id", commandId);
		parms.put("reply.content", content);
		parms.put("staff.mobileID", mobilID);
		parms.put("reply.createdAt", time);
		Log.i("-------url----------", url);
		Log.i("-------command.id----------", commandId);
		Log.i("-------reply.content----------", content);
		Log.i("-------staff.mobileID----------", mobilID);
		Log.i("-------reply.createdAt----------", time);
		return push(url, false, parms);
	}

	/**
	 * 
	 * @param url
	 * @param tType
	 *            all:所有 comm1:重要通知 comm2我要报告 consult:观众反馈 wea:天气预报 replay:回复
	 *            turn:签表 match:每日对阵
	 * @param maxID
	 * @param ids
	 * @param mobilID
	 * @return
	 * @throws Exception
	 */
	public static String polling(String url, String tType, String maxID,
			String ids, String mobileID, String needRefrush) throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("tType", tType);
		parms.put("maxID", maxID);
		if (ids != null && !"".equals(ids)) {
			parms.put("ids", ids);
			Log.i("-------ids----------", ids);
		}
		parms.put("mobileID", mobileID);
		parms.put("needRefrush", needRefrush);
		parms.put("version", "0");
		Log.i("-------version----------", "0");
		Log.i("-------needRefrush----------", needRefrush);
		Log.i("-------url----------", url);
		Log.i("-------tType----------", tType);
		Log.i("-------maxID----------", maxID);
		Log.i("-------mobileID----------", mobileID);
		return push(url, false, parms);
	}

	public static String pollSql(String url, String mobileID, String sql,
			String model, String needRefrush) throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("maxID", "-3");
		parms.put("ids", "-3");
		parms.put("mobileID", mobileID);
		parms.put("tType", "sqlStr");
		parms.put("params", sql);
		parms.put("model", model);
		parms.put("needRefrush", needRefrush);
		Log.i("-------needRefrush----------", needRefrush);
		Log.i("-------tType----------", "sqlStr");
		Log.i("-------params----------", sql);
		Log.i("-------model----------", model);
		Log.i("-------mobileID----------", mobileID);
		return push(url, false, parms);
	}

	public static String loadSql(String url, String mobileID, String sql)
			throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("mobileID", mobileID);
		parms.put("params", sql);
		Log.i("-------params----------", sql);
		Log.i("-------mobileID----------", mobileID);
		Log.i("-------url----------", url);
		return push(url, false, parms);
	}

	public static String execSql(String url, String mobileID, String sqlID)
			throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("mobileID", mobileID);
		parms.put("params", sqlID);
		Log.i("-------sqlID----------", sqlID);
		Log.i("-------mobileID----------", mobileID);
		Log.i("-------url----------", url);
		return push(url, false, parms);
	}

	public static SerInfoResponse execSerSql(String url, String mobileID,
			String sqlID, int model) {
		String mResult;
		try {
			mResult = execSql(url, mobileID, sqlID);
			Log.e("-------serverinfo content ------", mResult);
			SerInfoResponse resp = JsonParse.parseSerInfoResponse(mResult,
					model);
			if (resp != null && resp.success && resp.os != null
					&& resp.os.length > 0) {
				return resp;
			}
		} catch (Exception e) {
			Log.e("----------", "----------", e);
		}
		return null;
	}

	public static SerInfoResponse loadSerInfo(String url, String mobileID,
			String sql, int model) {
		String mResult;
		try {
			mResult = loadSql(url, mobileID, sql);
			Log.e("-------serverinfo content ------", mResult);
			SerInfoResponse resp = JsonParse.parseSerInfoResponse(mResult,
					model);
			if (resp != null && resp.success && resp.os != null
					&& resp.os.length > 0) {
				return resp;
			}
		} catch (Exception e) {
			Log.e("----------", "----------", e);
		}
		return null;
	}

	public static String loadReply(String url, String mobileID,
			String serverID, String mID) throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("serverID", serverID);
		parms.put("mobileID", mobileID);
		parms.put("mID", mID);
		Log.i("-------serverID----------", serverID);
		Log.i("-------mobileID----------", mobileID);
		Log.i("-------mID----------", mID);
		return push(url, false, parms);
	}

	public static String getVal(String str) {
		return str != null ? str : "";
	}

	public static String hasReply(String url, String mobileID, String serverID)
			throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("serverID", serverID);
		parms.put("mobileID", mobileID);
		Log.i("-------serverID----------", serverID);
		Log.i("-------mobileID----------", mobileID);
		return push(url, false, parms);
	}

	public static void uploadReply(String url, String mobileID,
			String replyBeans, DBHelper mDB) throws Exception {
		Log.i("-------replyBeans----------", String.valueOf(replyBeans));
		Log.i("-------mobileID----------", String.valueOf(mobileID));
		Log.i("-------url----------", String.valueOf(url));
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("replyBeans", replyBeans);
		parms.put("mobileID", mobileID);
		String res = push(url, false, parms);
		Log.i("-------res----------", String.valueOf(res));
		Response r = JsonParse.parseRespnse(res);
		if (r != null && r.success && r.id != null && !"".equals(r.id)) {
			String[] rids = r.id.split(",");
			for (int i = 0; i < rids.length; i++) {
				Log.i("-------id---------", String.valueOf(rids[i]));
				mDB.delUploadReply(rids[i]);
			}
		}
	}

	public static SerInfoResponse execSerSql2(String url, String mobileID,
			String sqlID, int model) {
		Log.e("------url---", url);
		String mResult;
		try {
			mResult = execSql2(url, mobileID, sqlID);
			Log.e("-------serverinfo content ------", mResult);
			SerInfoResponse resp = JsonParse.parseSerInfoResponse(mResult,
					model);
			if (resp != null && resp.success && resp.os != null
					&& resp.os.length > 0) {
				return resp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String execSql2(String url, String mobileID, String sqlID)
			throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("mobileID", mobileID);
		parms.put("params", sqlID);
		Log.i("-------sqlID----------", sqlID);
		Log.i("-------mobileID----------", mobileID);
		Log.i("-------url----------", url);
		return push(url, true, parms);
	}
	
	public static String execIMSql(String url, String mobileID, String strImIds)
	throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		parms.put("mobileID", mobileID);
		parms.put("imIds", strImIds);
		parms.put("params", "imsql");
		Log.i("-------mobileID----------", mobileID);
		Log.i("-------url----------", url);
		return push(url, true, parms);
	}

	public static SerInfoResponse execSerIMSql(String url, String mobileID,
			String strImIds, int model) {
//		Log.e("------url---", url);
		String mResult;
		try {
			mResult = execIMSql(url, mobileID, strImIds);
			Log.e("-------serverinfo content ------", mResult);
			SerInfoResponse resp = JsonParse.parseSerInfoResponse(mResult,
					model);
			if (resp != null && resp.success && resp.os != null
					&& resp.os.length > 0) {
				return resp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
